#include <dbus/dbus.h>
#include <stdio.h>
#include <iostream>
#include <stdlib.h>
#include "Xanguli.h"
#include "DBusProxy.h"
#include "IdGenerator.h"
#include "org_xanguli_Xanguli.h"
#include "org_freedesktop_DBus_Introspectable.h"
#include "ServerObject.h"
#include "Controller.h"
#include "org_xanguli_Controller.h"

#include <map>
#include <string>
#include "Variant.h"
#include "Marshal.h"

namespace Xanguli {

Xanguli::Xanguli(DBusConnection *bus) {
	this->bus = bus;
}

void Xanguli::run() {
	DBusError error;
	dbus_error_init(&error);
	DBusConnection *bus = dbus_bus_get(DBUS_BUS_SESSION, &error);

	dbus_bus_request_name(bus, "org.xanguli.Service", 0, &error);
	ServerObject* serverObject = new ServerObject();
	(*serverObject) << new org_xanguli_Xanguli<Xanguli> (new Xanguli(bus));
	ServerObject::register_object(bus, serverObject, "/Xanguli");
	while (dbus_connection_read_write_dispatch(bus, -1)) {
		;
	}
	// TODO cleanup
}

void Xanguli::CreateController(std::string& path) {
	ServerObject *so = new ServerObject();
	Controller *controller = new Controller();
	(*so) << (new org_xanguli_Controller<Controller> (controller));
	path = IdGenerator::newPath("org/xanguli/Controller");
	ServerObject::register_object(bus, so, path);
}

}

int main(int argc, char **argv) {
	Xanguli::Xanguli::run();
}
